<template>
  <GiFlexibleBox v-model="visible">
    <a-card title="权限组管理" :bordered="false" class="right">
      <template #extra>
        <a-space>
          <a-button type="primary" size="small" @click="openModel(false)">添加</a-button>
          <a-button v-if="selectedKeys.length > 0" type="primary" size="small" @click="onDeleteBatch(false)">
            批量删除
          </a-button>
        </a-space>
      </template>
      <div class="content">
        <a-table
          row-key="id"
          :loading="loading"
          :data="tableData"
          :scroll="{ x: '100%', y: '80%' }"
          size="small"
          v-model:columns="columns"
          :row-selection="{ type: 'checkbox', showCheckedAll: true }"
          v-model:selectedKeys="selectedKeys"
          :pagination="{
            showTotal: true,
            total: pagination.total,
            current: pagination.current,
            pageSize: pagination.pageSize
          }"
          @page-change="changeCurrent"
        >
          <template #status="{ record }">
            <a-switch v-model="record.status" size="medium">
              <template #checked>有效</template>
              <template #unchecked>无效</template>
            </a-switch>
          </template>
          <template #action="{ record }">
            <a-space>
              <a-button type="text" @click="openModel(record)" size="small">编辑 </a-button>
              <a-button type="text" size="small" @click="onDeleteBatch(record.id)"> 删除 </a-button>
            </a-space>
          </template>
        </a-table>
      </div>
    </a-card>
    <a-modal v-model:visible="editVisible" :title="title" unmount-on-close @before-ok="onAddOrEdit">
      <a-form ref="formRef" :model="form" size="medium" auto-label-width>
        <a-form-item
          label="权限组名称"
          field="name"
          :rules="[
            { required: true, message: '请输入权限组名称' },
            { min: 2, max: 10, message: '长度在 2 - 10个字符' }
          ]"
          :validate-trigger="['change', 'input', 'blur', 'focus']"
        >
          <a-input placeholder="请输入权限组名称" v-model="form.name" allow-clear></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </GiFlexibleBox>
</template>

<script setup>
import { usePagination } from '@/hooks'
import { permissionGroupList, permissionGroupDelete, permissionGroupAdd, permissionGroupEdit } from '@/apis'
import { Message, Modal } from '@arco-design/web-vue'

const visible = ref(true)
const changeVisible = () => {
  visible.value = !visible.value
}

const columns = [
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    render: ({ record }) => {
      return record.created_at || '--'
    }
  },
  {
    title: '操作',
    slotName: 'action'
  }
]

const loading = ref(false)
const listParams = {
  page: 1,
  pageSize: 10
}
const tableData = ref([])
const selectedKeys = ref([])

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 15 })

const formRef = ref()
const title = computed(() => (form.id ? '编辑权限组' : '新增权限组'))
const editVisible = ref(false)

const form = reactive({
  id: undefined,
  name: ''
})

const getTableData = async () => {
  loading.value = true
  listParams.page = pagination.current
  listParams.pageSize = pagination.pageSize
  const res = await permissionGroupList(listParams)
  tableData.value = res.data.data
  setTotal(res.data.total)
  loading.value = false
}
getTableData()

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

// 删除数据
const onDeleteBatch = (id) => {
  Modal.warning({
    title: '提示',
    content: '是否确认删除？',
    hideCancel: false,
    onOk: () => {
      loading.value = true
      const ids = id ? [id] : selectedKeys.value
      const apiArr = ids.map((item) => {
        return permissionGroupDelete({ id: item })
      })
      Promise.all(apiArr)
        .then(() => {
          selectedKeys.value = []
          Message.success('删除成功')
          getTableData()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

const openModel = (item) => {
  form.id = item?.id || undefined
  form.name = item?.name || ''
  editVisible.value = true
}

const onAddOrEdit = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const api = form.id ? permissionGroupEdit : permissionGroupAdd
  await api(form)
  Message.success('操作成功')
  getTableData()
  return true
}

defineExpose({ changeVisible })
</script>

<style lang="scss" scoped>
.right {
  width: 600px;
  height: 100%;
  border-left: 1px solid $color-border;
  display: flex;
  flex-direction: column;
  :deep(.arco-card-body) {
    width: 570px;
    flex: 1;
  }
  .content {
    height: 100%;
    box-sizing: border-box;
  }
}
</style>
